/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.unal.bioingenium.kbmed.data.loader;

import co.edu.unal.bioingenium.kbmed.data.PhysicalDocument;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Alejandro Riveros Cruz
 */
public class XMLLoader implements DocumentLoader {
    private final String type = "XML";

    /**
     * 
     */
    public static final String CONTENT_SEPARATOR = "::";

    /**
     * 
     */
    public XMLLoader() {
    }

    /**
     * 
     * @param path
     * @return
     */
    @Override
    public PhysicalDocument parseDocument(String corpusPath, String fileName) {
        try {
            File file = new File(corpusPath + fileName);
            if (!file.isFile()) {
                Logger.getLogger(TXTLoader.class.getName()).log(Level.WARNING, "The file {0}don''t exist.", corpusPath + fileName);
                return null;
            }
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document DOMDocument = documentBuilder.parse(corpusPath + fileName);
            Element documentElement = DOMDocument.getDocumentElement();
            NodeList nodeList = documentElement.getElementsByTagName("*");
            PhysicalDocument document = new PhysicalDocument(fileName);
            StringBuilder tempContent = new StringBuilder();
            if (nodeList != null) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    tempContent.append(nodeList.item(i).getNodeName()).append(CONTENT_SEPARATOR).append(nodeList.item(i).getTextContent()).append("\n");
                }
            }
            document.setType(type);
            document.setSize(file.length());
            document.setLastModified(new Date(file.lastModified()));
            document.setContent(tempContent.toString());
            return document;
        } catch (ParserConfigurationException pce) {
            Logger.getLogger(XMLLoader.class.getName()).log(Level.SEVERE, "Error while parsing XML file", pce);
        } catch (SAXException saxe) {
            Logger.getLogger(XMLLoader.class.getName()).log(Level.SEVERE, "Error while parsing XML file", saxe);
        } catch (IOException ioe) {
            Logger.getLogger(XMLLoader.class.getName()).log(Level.SEVERE, "Error while parsing XML file", ioe);
        }
        return null;
    }
}
